import { Injectable } from '@nestjs/common';
import * as qiniu from 'qiniu';

@Injectable()
export class QiniuService {
  private mac: qiniu.auth.digest.Mac;
  private options: qiniu.rs.PutPolicyOptions;
  private config: qiniu.conf.Config;

  private readonly accessKey = 'MKZJl0xAzss9hiuPW8_m__JU9XE3ekIFqLFrbmb-';
  private readonly secretKey = 'ZpqOegOTuuJU1hYR1MZow5XwqueWDsWAaomXKUVa';
  private readonly bucket = 'rogiblog';
  private readonly domain = 'https://img.cmczya.cn'; // 例如 http://cdn.example.com

  constructor() {
    this.mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);
    this.options = { scope: this.bucket };
    this.config = new qiniu.conf.Config();
    this.config.zone = qiniu.zone.Zone_z2; // 修改为你实际使用的区域
  }

  getUploadToken(): string {
    const putPolicy = new qiniu.rs.PutPolicy(this.options);
    return putPolicy.uploadToken(this.mac);
  }

  async uploadFile(filePath: string, key: string): Promise<string> {
    const formUploader = new qiniu.form_up.FormUploader(this.config);
    const putExtra = new qiniu.form_up.PutExtra();
    const uploadToken = this.getUploadToken();

    return new Promise((resolve, reject) => {
      formUploader.putFile(uploadToken, key, filePath, putExtra, (err, body, info) => {
        if (err || info.statusCode !== 200) {
          reject(err || body);
        } else {
          resolve(`${this.domain}/${body.key}`);
        }
      });
    });
  }
}
